#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import os
import sys

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.learn.learn import router as learn_router
from app.lesson.lesson import router as lesson_router
from app.db.database import db

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    print("=" * 50)
    print("PIC_UI_API 正在启动...")
    print("=" * 50)
    
    # 初始化数据库
    try:
        db.init_database()
        print("✓ 数据库初始化成功")
        
        # 检查数据库连接
        learn_count = db.get_table_count("learn")
        lesson_count = db.get_table_count("lesson")
        print(f"✓ 数据库连接正常")
        print(f"  - 学习课程数量: {learn_count}")
        print(f"  - 课程数量: {lesson_count}")
        
    except Exception as e:
        print(f"✗ 数据库初始化失败: {str(e)}")
        raise
    
    print("✓ 应用启动完成")
    print("=" * 50)
    
    yield
    
    # 关闭时执行
    print("PIC_UI_API 正在关闭...")
    print("✓ 应用已安全关闭")

# 创建FastAPI应用实例
app = FastAPI(
    title="PIC_UI_API",
    description="学习课程管理系统API",
    version="1.0.0",
    docs_url="/",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(learn_router, prefix="/api")
app.include_router(lesson_router, prefix="/api")

@app.exception_handler(404)
async def not_found_handler(request, exc):
    """404错误处理"""
    return JSONResponse(
        status_code=404,
        content={
            "error": "Not Found",
            "message": "请求的资源不存在",
            "path": str(request.url.path)
        }
    )

@app.exception_handler(500)
async def internal_error_handler(request, exc):
    """500错误处理"""
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal Server Error",
            "message": "服务器内部错误",
            "path": str(request.url.path)
        }
    )

if __name__ == "__main__":   
    uvicorn.run(
        "main:app",
        host = "127.0.0.1",
        port = 9001,
        reload = True,
        log_level = "info"
    )
